package com.commander;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.amap.api.navi.model.RouteOverlayOptions;
import com.amap.api.navi.view.DirectionView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.commander.utils;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BasicNaviActivity extends BaseActivity  {
    OkHttpClient client = new OkHttpClient();
    public String token;
    public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
        Drawable drawable = ContextCompat.getDrawable(context, drawableId);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            drawable = (DrawableCompat.wrap(drawable)).mutate();
        }
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
    private static BitmapDescriptor addTextToBitmap(Context context, Bitmap bitmap, String text) {
        Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(context.getResources().getColor(android.R.color.black)); // 设置文本颜色
        textPaint.setTextSize(20); // 设置文本大小

        // 设置文本布局
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        StaticLayout staticLayout = new StaticLayout(text, textPaint, width,
                Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);

        // 在 Bitmap 上绘制 SVG 图片和文本
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);

        canvas.save();
        canvas.translate(0, height - staticLayout.getHeight()); // 调整文本位置
        staticLayout.draw(canvas);
        canvas.restore();

        // 将 Bitmap 转换为 BitmapDescriptor
        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }
    String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("token", token)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_basic_navi);
        mAMapNaviView = findViewById(R.id.navi_view);
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        var target = intent.getExtras().getBundle("target");
        token=target.getString("token");
        var latitude = target.getDouble("latitude");
        var longitude = target.getDouble("longitude");
        new Thread(() -> {
            HttpUrl url = HttpUrl.parse("https://lingjlkdyt.abuav.com.cn:8098/patrol-admin/patrol/fire/facility/getFireFacilityLocationData").newBuilder()
                    .addQueryParameter("centerLng", longitude + "")
                    .addQueryParameter("centerLat", latitude + "")
                    .addQueryParameter("radius", "950")
                    .build();
            try {
                String responseBody = get(url.toString());
                JSONObject jsonObject = new JSONObject(responseBody);
                Object data = jsonObject.get("data");
                if (data instanceof JSONArray) {
                    MarkerOptions markerOptions = new MarkerOptions();
                    if(((JSONArray) data).length()>10){
                        Bitmap bitmap   =getBitmapFromVectorDrawable(this,R.drawable.xhs);
                        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                        for (int i = 0; i < ((JSONArray) data).length(); i++) {
                            JSONObject item = ((JSONArray) data).getJSONObject(i);
                        }

                    }else{
                        for (int i = 0; i < ((JSONArray) data).length(); i++) {
                            JSONObject item = ((JSONArray) data).getJSONObject(i);
                            Bitmap bitmap   =getBitmapFromVectorDrawable(this,R.drawable.xhs);
                            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
//                            BitmapDescriptor textBitmapDescriptor = addTextToBitmap(this, bitmap, item.getString("ownerAddress"));
                            markerOptions.position(new LatLng(item.getDouble("lat"), item.getDouble("lng")));
                            markerOptions.title(item.getString("ownerAddress"))
                                    .icon(bitmapDescriptor);
                            mAMapNaviView.getMap().addMarker(markerOptions);
                        }
                        mAMapNaviView.setOnMarkerClickListener((marker)->{
                            marker.showInfoWindow();
                            return  true;
                        });
                    }


                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }).start();
        mAMapNaviView.onCreate(savedInstanceState);
        AMapNaviViewOptions aMapNaviViewOptions = new AMapNaviViewOptions();
        aMapNaviViewOptions.setAutoDisplayOverview(true);
        aMapNaviViewOptions.setSettingMenuEnabled(true);
        mAMapNaviView.setViewOptions(aMapNaviViewOptions);
        mAMapNaviView.setAMapNaviViewListener(this);
    }


}
